package AdminService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/grand"
	"strings"
	"time"
)

func PersonUpdate(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	avatar := r.GetString("avatar")
	password := r.GetString("password")
	avatar = strings.ReplaceAll(avatar, g.Cfg().GetString("upload.PhotoPreFix"), "")
	updateData := g.Map{
		"avatar":    avatar,
		"nickname":  r.GetString("nickname"),
		"realname":  r.GetString("realname"),
		"remark":    r.GetString("remark"),
		"update_at": time.Now().Unix(),
	}

	if password != "" {
		passwordSalt := grand.Letters(10)
		updateData["password_salt"] = passwordSalt
		updateData["password"] = tools.EncryptPassword(password, passwordSalt)
	}

	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(r.GetCtx(), req.TableName).Where(
		"id",
		req.AdminId,
	).Update(updateData)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row < 1 {
		return response.FailByRequestMessage(nil, "编辑失败")
	}
	return response.SuccessByRequestMessage(nil, "编辑成功")
}
